import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Bully, BullySubjectService } from 'app/shared/service';
import { SYSTEM_EVENT, MESSAGE_CHANNEL } from 'app/app.constants';
import { HttpClient } from '@angular/common/http';
import { ConfigService } from 'app/config/config.service';
import { USER_API_URL } from 'app/app.constants';
import { SystemService } from '../service/system.service';
import { PublicService } from 'app/public/public.service';

@Injectable({
    providedIn: 'root'
})
export class LoginService {
    private apiUrl_user_online = USER_API_URL;
    constructor(
        private router: Router,
        private bully: BullySubjectService,
        private config: ConfigService,
        private http: HttpClient,
        private ss: SystemService,
        private pub: PublicService
    ) {}
    /**
     * check token
     */
    autoAccessToken() {
        // 还要判断这个token 过期没有
        if (!localStorage.getItem('access_token')) {
            this.logIn();
            return false;
        }
        return true;
    }

    /**
     * return access_token
     */
    getAccessToken() {
        this.autoAccessToken();
        return localStorage.getItem('access_token');
    }

    /**
     * login
     */
    logIn() {
        // 还有登录时间戳
        this.pub.optionsList = [];
        localStorage.removeItem('access_token_stamp');
        localStorage.removeItem('access_token');
        this.router.navigate(['/login']);
    }

    /**
     * 登出
     */
    logOut() {
        const userId = localStorage.getItem('user_id');
        if (userId) {
            const url = `${this.apiUrl_user_online}/userMgt/user/logoutdestroytoken/${userId}`;
            this.http.get<any>(url).subscribe(res => {
                this.logIn();
                setTimeout(() => {
                    const data: Bully = { type: SYSTEM_EVENT.CCM_WIN_CHANGE, data: false };
                    this.bully.registerBroadcastSend(MESSAGE_CHANNEL.CCM_CHANNEL, data);
                }, 1000);
            });
        }
    }
}
